const { Service } = require('egg');
const moment = require('moment');
const user_role_table = 'user_role_relationship';
const role_permission_table = 'role_permission_relationship';
const permission_table = 'permission';

class RelationshipService extends Service {

  // 分配角色
  async createUserAndRole(user_id, role_id) {
    try {
      const time = moment();
      const { id } = this.ctx.session;

      const is_repeat = await this.app.knex().select('*').from(user_role_table);

      if (is_repeat) {
        throw new Error('');
      }
      const instance = {
        user_id, role_id,
        create_time: moment(time).form('YYYY-MM-DD HH:mm:ss'),
        update_time: moment(time).form('YYYY-MM-DD HH:mm:ss'),
        create_by: id,
        update_by: id,
        is_delete: 0,
      };

      const data = await this.app.knex().insert(instance).returning('id');
      instance.id = data[0];
      return instance;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 更新当前角色
  async updateUserAndRole(user_id, role_id) {
    try {
      const { id } = this.ctx.session;
      const instance = await this.app.knex().select('*').from(user_role_table)
        .where({ user_id });
      if (!instance) {
        throw new Error('当前用户尚未分配角色');
      }

      instance.role_id = role_id;

      await this.app.knex(user_role_table).update(instance).where({ user_id });
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 删除当前角色
  async deleteUserAndRole(user_id) {
    try {
      const time = moment();
      const { id } = this.ctx.session;
      await this.app.knex(user_role_table)
        .update({ is_delete: 1, update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'), update_by: id })
        .where({ user_id, is_delete: 0 });

      return;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 获取角色权限
  async getRoleAndPermission(role_id) {
    try {
      const data = await this.app.knex().select('t2.uuid', 't2.name', 't2.key', 't2.url', 't2.type', 't2.parent_id')
        .from(`${role_permission_table} as t1`)
        .leftJoin(`${permission_table} as t2`, () => {
          this.on('t1.permission_id', '=', 't2.uuid');
        })
        .where('t1.role_id', role_id)
        .andWhere('t1.is_delete', 0);

      const ability = data.filter(f => {
        return f.type === 1;
      });

      const menu = data.filter(f => {
        return f.type === 2;
      });

      return {
        ability,
        menu,
      };
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 角色配置权限
  async createRoleAndPermission(role_id, permission_id) {
    try {
      const { id } = this.ctx.session;
      const time = moment();
      const instances = [];

      for (const p of permission_id) {
        const instance = {
          role_id, permission_id: p,
          create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          create_by: id,
          update_by: id,
          is_delete: 0,
        };

        instances.push(instance);
      }

      await this.app.knex(role_permission_table).insert(instances);

      return;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 更新角色权限
  async updateRoleAndPermission(role_id, permission_id) {
    try {
      await this.app.knex(role_permission_table).update({ is_delete: 1 }).where({ role_id });
      const { id } = this.ctx.session;
      const time = moment();
      const instances = [];

      for (const p of permission_id) {
        const instance = {
          role_id, permission_id: p,
          create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
          create_by: id,
          update_by: id,
          is_delete: 0,
        };

        instances.push(instance);
      }

      await this.app.knex(role_permission_table).insert(instances);

      return;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 删除角色权限
  async deleteRoleAndPermission(role_id, permission_id) {
    try {
      const time = moment();
      const { id } = this.ctx.session;
      await this.app.knex(role_permission_table)
        .update({ is_delete: 1, update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'), update_by: id })
        .whereIn('permission_id', permission_id)
        .andWhere({ role_id, is_delete: 0 });

      return;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }


  async init() {
    try {
      const role_lists = await this.app.knex('role').select('uuid', 'name').where({ name: '超级管理员' })
        .orWhere({ name: '管理员' });


      const user_lists = await this.app.knex('user').select('uuid', 'name', 'login_name').where({ name: 'superAdmin' })
        .orWhere({ login_name: 'admin' });

      const list = [];

      for (const u of user_lists) {
        if (u.login_name === 'superAdmin') {
          const f = role_lists.find(f => {
            return f.name === '超级管理员';
          });

          list.push({
            user_id: u.uuid,
            role_id: f.uuid,
            create_by: '-1',
            update_by: '-1',
            is_delete: 0,
          });
        } else {
          const f = role_lists.find(f => {
            return f.name === '超级管理员';
          });

          list.push({
            user_id: u.uuid,
            role_id: f.uuid,
            create_by: '-1',
            update_by: '-1',
            is_delete: 0,
          });
        }
      }


      if (list.length > 0) {
        await this.app.knex(user_role_table).insert(list);
      }

      return list;
    } catch (error) {
      console.log(error);
      throw error;
    }
  }
}

module.exports = RelationshipService;

